/**
 * 自定义节点重叠
 * @author houjinhui
 */
import G6 from '@antv/g6'
import { message } from 'ant-design-vue'

interface KeyValue {
  [key: string]: any
}

/**
 * 自定义画布布局
 */
export default function registerScaleLayout() {
  // 基础弧线布局
  G6.registerLayout('scale', {
    scale: 1.1,
    // 定义自定义行为的默认参数，会与用户传入的参数进行合并
    getDefaultCfg() {
      return {}
    },
    /**
     * 初始化
     * @param {Object} data 数据
     */
    init(data: any) {
      const currentLayout = this // this 指向当前布局
      currentLayout.nodes = data.nodes
      currentLayout.edges = data.edges
    },
    /**
     * 执行布局
     */
    execute() {
      const currentLayout: any = this
      const { nodes } = currentLayout
      const nodesLength: number = nodes.length
      // 为每一个节添加布局信息
      try {
        let xMean = 0
        let yMean = 0
        nodes.forEach((node: any) => {
          xMean += node.x
          yMean += node.y
        })

        xMean /= nodesLength
        yMean /= nodesLength

        nodes.forEach((node: any) => {
          const dx = (node.x - xMean) * this.scale
          const dy = (node.y - yMean) * this.scale
          node.x = xMean + dx
          node.y = yMean + dy
        })
      } catch {
        message.error('布局失败！')
      }
    },

    /**
     * 根据传入的数据进行布局
     * @param {Object} data 数据
     */
    layout(data: any) {
      const currentLayout = this
      currentLayout.init(data)
      currentLayout.execute()
    },
    /**
     * 更新布局配置，但不执行布局
     * @param {Object} cfg 需要更新的配置项
     */
    updateCfg(cfg: any) {
      const currentLayout = this
      G6.Util.mix(currentLayout, cfg)
    },
    /**
     * 销毁
     */
    destroy() {
      const currentLayout = this
      currentLayout.positions = null
      currentLayout.nodes = null
      currentLayout.edges = null
      currentLayout.destroyed = true
    },
  })
}
